<template>
  <div>
    <h2>单词列表</h2>
    <input type="file" @change="handleFileChange" accept=".json" />
    <div v-if="errorMessage" class="error">{{ errorMessage }}</div>
    <WordCard v-for="word in words" :key="word.id" :word="word"/>
  </div>
</template>

<script>
import WordCard from './WordCard.vue';
import { mapState, mapActions } from 'vuex';

export default {
  components: { WordCard },
  computed: {
    ...mapState(['words'])
  },
  methods: {
    ...mapActions(['importWords']),
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.importWords(file)
            .then(() => {
              this.errorMessage = '';
            })
            .catch((error) => {
              this.errorMessage = '导入失败，请检查文件格式是否正确。';
              console.error(error);
            });
      }
    }
  },
  data() {
    return {
      errorMessage: ''
    };
  }
}
</script>

<style scoped>
.error {
  color: red;
  margin-bottom: 10px;
}
</style>